import { useAppStore } from "../stores/modules/app";

// 把路径转换成驼峰命名
export const pathToCamel = (path: string): string => {
  return path.replace(/\/(\w)/g, (all, letter) => letter.toUpperCase());
};

// 转换文件大小格式
export const convertSizeFormat = (size: number): string => {
  const unit = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
  let index = Math.floor(Math.log(size) / Math.log(1024));
  let newSize = size / Math.pow(1024, index);

  // 保留的小数位数
  return newSize.toFixed(2) + " " + unit[index];
};

// 获取svg图标(id)列表
export const getIconList = (): string[] => {
  const rs: string[] = [];
  const list = document.querySelectorAll("svg symbol");
  for (let i = 0; i < list.length; i++) {
    rs.push(list[i].id);
  }
  return rs;
};

// 全局组件安装
// export const withInstall = <T extends Component>(component: T, alias?: string) => {
//   const comp = component as any
//   comp.install = (app: App) => {
//     app.component(comp.name || comp.displayName, component)
//     if (alias) {
//       app.config.globalProperties[alias] = component
//     }
//   }
//   return component as T & Plugin
// }

// 数字千分位格式化
export function numberToCurrencyNo(value: number): string | number {
  if (!value) {
    return "-";
  }
  // 获取整数部分
  const intPart = Math.trunc(value);
  // 整数部分处理，增加,
  const intPartFormat = intPart
    .toString()
    .replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
  // 预定义小数部分
  let floatPart = "";
  // 将数值截取为小数部分和整数部分
  const valueArray = value.toString().split(".");
  if (valueArray.length === 2) {
    // 有小数部分
    floatPart = valueArray[1].toString(); // 取得小数部分
    return intPartFormat + "." + floatPart;
  }
  return intPartFormat + floatPart;
}

export const secTotime = (s: number) => {
  var t = "";
  if (s > -1) {
    var hour = Math.floor(s / 3600);
    var min = Math.floor(s / 60) % 60;
    var sec = s % 60;
    if (hour < 10) {
      t = hour + "小时";
    } else {
      t = hour + "小时";
    }
    if (min < 10) {
      t += "0";
    }
    t += min + "分钟";
    if (sec < 10) {
      t += "0";
    }
    t += sec.toFixed(0) + "秒";
  }
  return t;
};

// 获取本地图片资源url
export const requireImgUrl = (name: string) => {
  return new URL(`../../assets/images/dashboard/${name}.png`, import.meta.url)
    .href;
};

// 根据typeCode获取字典数据列表
export const getDictDataList = (typeCode: string) => {
  let list: any = [];
  if (typeCode) {
    const dictList = useAppStore().dictList;
    list = dictList.filter((element: any) => element.typeCode === typeCode);
  }
  return list;
};

export const detectZoom = () => {
  let ratio = 0,
    screen = window.screen as any,
    ua = navigator.userAgent.toLowerCase();
  if (window.devicePixelRatio !== undefined) {
    ratio = window.devicePixelRatio;
  } else if (~ua.indexOf("msie")) {
    if (screen.deviceXDPI && screen.logicalXDPI) {
      ratio = screen.deviceXDPI / screen.logicalXDPI;
    }
  } else if (
    window.outerWidth !== undefined &&
    window.innerWidth !== undefined
  ) {
    ratio = window.outerWidth / window.innerWidth;
  }
  if (ratio) {
    ratio = Math.round(ratio * 100);
  }
  return ratio;
};

/**
 * @description: getRenderDate获取数组日期
 * @param {Number} nowyear  必填 获取今年年份
 * @param {Number} nowMonth  必填 获取起始月份
 * @param {Number} startTime  必填 获取起始日期
 * @param {Number} whichNumbers 选填  获取需要未来几天的天数
 */
export const getRenderDate = (
  nowyear,
  nowMonth,
  startTime,
  whichNumbers = 7
) => {
  console.log(nowyear);

  let date = new Date(nowyear, nowMonth, 0);
  let time = date.getDate() > 9 ? date.getDate() : "0" + date.getDate(); //本月最后一天
  let str = 0;
  let fulldayArr = [];
  let dayArr = [];
  for (let i = 0; i < whichNumbers; i++) {
    str =
      (startTime + i > time ? startTime + i - <any>time : startTime + i) <= 10
        ? "0" +
        (startTime + i > time ? startTime + i - <any>time : startTime + i)
        : startTime + i > time
          ? startTime + i - <any>time
          : startTime + i; //当前日期为???号
    let fullday = nowyear + "-" + nowMonth + "-" + str;
    let day = nowMonth + "-" + str;
    fulldayArr.push(fullday);
    dayArr.push(day);
  }

  return {
    fulldayArr,
    dayArr,
  };
};
/**
 * @description: extractTree扁平化操作
 * @param {Array} arrs     必填
 * @param {String} childs  必填
 * @param {Array} attrArr  选填  说明:只对arrs的某一个或多个字段扁平化，例子 attrArr=['id','pid']
 * @return {Array}
 */
//以下注释是extractTree(List, 'children') 执行时
// 对象数组扁平化
export const extractTree = (arrs, childs, attrArr?) => {
  let attrList = []; //存储数组对象的key
  if (!Array.isArray(arrs) && !arrs.length) return []; //如果arrs不是数组对象则直接退出
  if (typeof childs !== "string") return []; //定义第二参数必须为字符串
  if (!Array.isArray(attrArr) || (Array.isArray(attrArr) && !attrArr.length)) {
    attrList = Object.keys(arrs[0]); //存储数组对象的key,这里attrList=["id","pid","name","children"]
    if (attrList.indexOf(childs) !== -1) {
      //如果第二参数是children
      attrList.splice(attrList.indexOf(childs), 1); //那么就把attrList的children去掉，此时就变成attrList=["id","pid","name"]
    }
  } else {
    attrList = attrArr;
  }
  let list = [];
  const getObj = (arr) => {
    //递归操作
    //arr = arrs
    arr.forEach((row) => {
      let obj = {};
      //attrList=["id","pid","name"]
      attrList.forEach((item) => {
        obj[item] = row[item] ? row[item] : "";
      });
      list.push(obj);
      if (row[childs]) {
        //如果有children这个字段，说明有下一级
        getObj(row[childs]); //递归
      }
    });
    return list;
  };
  return getObj(arrs);
};

/**
 * 将给定的列表去重并返回新的列表
 * @param list 列表数组
 * @returns 去重后的列表
 */
export const reduceTree = (list) => {
  let obj = {};
  let rlist = [];
  rlist = list.reduce((item, next) => {
    obj[next.id] ? "" : (obj[next.id] = true && item.push(next));
    return item;
  }, []);
  return rlist;
};

// 根据给定的数据，根据pid字段和child字段生成树结构
export const makeTree = (data: any[], pid: string, child: string) => {
  // 筛选出pid为2的父节点
  let parents = data.filter((p) => p[pid] == 2);
  // 筛选出pid不为0的子节点
  let children = data.filter((c) => c[pid] !== 0);

  // 将数据转换为树结构
  dataToTree(parents, children);
  return parents;

  // 将数据转换为树结构的函数
  function dataToTree(parents: any[], children: any[]) {
    // 遍历父节点数组
    parents.map((p) => {
      // 遍历子节点数组
      children.map((c, i) => {
        // 如果子节点的pid等于父节点的id
        if (c[pid] === p.id) {
          // 复制一份子节点数组
          let _children = JSON.parse(JSON.stringify(children));
          // 移除当前子节点
          _children.splice(i, 1);
          // 递归处理子节点
          dataToTree([c], _children);
          // 如果父节点存在child字段，则将子节点添加到child数组中；否则创建一个新的child数组，并将子节点添加进去
          if (p[child]) {
            p[child].push(c);
          } else {
            p[child] = [c];
          }
        }
      });
    });
  }
}

export const fillZero = (str) => {
  var realNum;
  if (str < 10) {
    realNum = "0" + str;
  } else {
    realNum = str;
  }
  return realNum;
};

export const renderStatus = (str) => {
  let s;
  if (str == "INFO") {
    s = "普通";
  } else if (str == "ERROR") {
    s = "紧急";
  } else {
    s = "告警";
  }

  return s;
};

export const renderDate = (jsonData) => {
  let now = new Date(jsonData);
  let hour = now.getHours(); //获取当前小时数(0-23)
  let minute = now.getMinutes(); //获取当前分钟数(0-59)
  let second = now.getSeconds(); //获取当前秒数(0-59)
  let nowTime = "";
  nowTime = fillZero(hour) + ":" + fillZero(minute) + ":" + fillZero(second);
  return nowTime;
};


export const renderClamp = (
  minValue = 16,
  maxValue = 32,
  minViewportPx = 1920,
  maxViewportPx = 3840
) => {
  let minValuePx = minValue;
  let maxValuePx = maxValue;

  const toRem = (value) => +(value / 16)?.toFixed(3);
  const toPx = (value) => +value?.toFixed(3);
  const switchToCurrentValue = (value) => toPx(value);
  let minViewport = switchToCurrentValue(minViewportPx);
  let maxViewport = switchToCurrentValue(maxViewportPx);

  const variablePart = (maxValuePx - minValuePx) / (maxViewport - minViewport);
  const constant = parseFloat(
    ((maxValuePx - maxViewport * variablePart) / 16).toFixed(3)
  );
  return `clamp(${toRem(minValue)}rem,${constant ? ` ${constant}rem +` : ""} ${parseFloat((100 * variablePart).toFixed(2))}vw, ${toRem(maxValue)}rem)`;
};


